X

Html/Css

Css Transitions Triggered by JavaScript

September 25, 2021

/*

Css Transitions Triggered by JavaScript


*/

Using Css transitions with JavaScript is awesome. You can declare a transition in css, then trigger it with a javascript event or just plain javascript. Let's say I wanted to transition the width of a div. The transition property is the width, the duration is 0.6s, the timing function is ease-out & the delay is 1s.

Code for the first css transition div

In the javascript, I would change the width of the div & the transition would play when the browser is reloaded.

Js code for transitioning the first div.

/*

Transitions on Events


*/

You can trigger transitions on javascript events. You can click the div & trigger the transition.

Css code for 2nd div transition.
Js code for 2nd transitioning div.

/*

Triggering Multiple Transitions


*/

Let's say we have two transitions we want to trigger on click. The width & the background color. We would declare both transitions in the css code.

Css code for 3rd div transition.

Then with javascript, specify what we want the properties new values to be on click.

Js code for 3rd div transition.

/*

Transitioning a Property by Clicking Another Element


*/

You don't have to click the element that the transition is on to trigger the transition. You can click a completely different element for any transition you want to do. Let's say we have a button with the div we were using before.

Css code for 4th div transition.

When I click the button, the width & the background color of the div will transition.

Js code for 4th transition.

This can make for some really cool transitions. The best part is it's surprisingly easy. This is an example project.

About the Author

Christopher Howard

Chris is a Javascript developer with a minor in UI design. He values programming in vanilla code. Fill out the form below to contact him.